<template>
	<view class="page-wrapper" :style="{paddingTop: `${getSystemInfo.navBarHeight || 70}px`}">
		<navBar title="个人信息" />
		<view class="item">
			<view class="item-title">个人信息设置</view>
			<u-cell-group :border="false">
				<u-cell :border="false" title="注册时间" :value="personalInfo.createdTime" :titleStyle="titleStyle"
					:rightIconStyle="rightIconStyle"></u-cell>
				<u-cell :border="false" title="头像" :titleStyle="titleStyle" isLink :rightIconStyle="rightIconStyle"
					@click="uploadAvatar">
					<image :src="personalInfo.headImgUrl?personalInfo.headImgUrl:defaultHeadImgUrl" slot="value"
						class="u-slot-value head-img"></image>
				</u-cell>
				<u-cell :border="false" title="昵称" :value="personalInfo.nickname" :titleStyle="titleStyle" isLink
					:rightIconStyle="rightIconStyle" @click="editName('nickName',personalInfo)"></u-cell>
				<u-cell :border="false" title="生日" :value="personalInfo.birthday" :titleStyle="titleStyle" isLink
					:rightIconStyle="rightIconStyle" @click="chooseBirthday"></u-cell>
				<u-cell :border="false" title="司机姓名" :value="personalInfo.name" :titleStyle="titleStyle" isLink
					:rightIconStyle="rightIconStyle" @click="editName('driverName',personalInfo)"></u-cell>
			</u-cell-group>
		</view>
		<view class="item" @click="goDetail('/minePack/user/accountSetting/shippingAddress')">
			<view class="one-line">
				<view class="name">收货地址</view>
				<view class="setting"><uni-icons type="right" class="u-setting"></uni-icons></view>
			</view>
		</view>
		<!-- 第二阶段再显示对应功能 -->
		<view class="item">
			<view class="item-title">账号安全设置</view>
			<u-cell-group :border="false">
				<u-cell :border="false" title="手机号码" :value="personalInfo.mobile" :titleStyle="titleStyle" isLink
					:rightIconStyle="rightIconStyle" @click="goAccount('phone')"></u-cell>
				<u-cell :border="false" title="重置密码" value="重置登录密码" :titleStyle="titleStyle" isLink
					:rightIconStyle="rightIconStyle" @click="goAccount('pass')"></u-cell>
				<u-cell :border="false" title="微信账号"
					:value="personalInfo.wechatBindFlag==='Y'&& personalInfo.wechatAccount?personalInfo.wechatAccount:'绑定微信'"
					:titleStyle="titleStyle" isLink :rightIconStyle="rightIconStyle"></u-cell>
			</u-cell-group>
		</view>
		<view class="item">
			<view class="one-line" @click="carAttestation(personalInfo.carCertState)">
				<view class="name">车辆认证</view>
				<view class="setting">
					<view class="do" :class="personalInfo.carCertState===0?'undo':''">
						{{setStatus(personalInfo.carCertState)}}
					</view>
					<uni-icons type="right" class="u-setting"></uni-icons>
				</view>
			</view>
		</view>
		<view class="item">
			<view class="one-line" @click="goDetail('/minePack/user/accountSetting/feedback')">
				<view class="name">功能反馈</view>
				<view class="setting"><uni-icons type="right" class="u-setting"></uni-icons></view>
			</view>
		</view>
		<view class="action-bottom">
			<u-button text="退出登录" color="#CF1A1B" @click="show=true"></u-button>
		</view>
		<u-datetime-picker ref="datetimePicker" :show="showDatePicker" v-model="birthdayDate" mode="date"
			@cancel="showDatePicker=false" @confirm="getBirthdayDate" :minDate="-2208988800000"
			:maxDate="new Date().getTime()"></u-datetime-picker>
		<u-modal :show="show" title="您确定要退出登录吗?" :showCancelButton="true" cancelText="取消" confirmText="确定"
			confirmColor="#CF1A1B" @confirm="quitAPP" @cancel="show = false">
		</u-modal>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapMutations
	} from 'vuex'
	import {
		baseUrl
	} from '@/common/config'
	import navBar from '@/components/navBar.vue'
	export default {
		components: {
			navBar
		},
		data() {
			return {
				titleStyle: {
					'fontSize': '28rpx',
					'fontWeight': '400',
					'color': 'rgba(0, 0, 0, 0.65)'
				},
				rightIconStyle: {
					'fontSize': '14px'
				},
				resetPwd: '重置登录密码',
				personalInfo: {
					createdTime: '',
					headImgUrl: '',
					nickName: '',
					birthday: '请选择生日',
					mobile: '',
					wechatAccount: '绑定微信',
					carCertState: ''
				},
				defaultHeadImgUrl: 'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/mine/user_avatar.png',
				showDatePicker: false,
				birthdayDate: '',
				show: false
			}
		},
		methods: {
			...mapMutations('user', ['setToken', 'setUserInfo']),
			...mapMutations('global', ['setNowLocation', 'setLocation']),
			//上传头像
			uploadAvatar() {
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.uploadFile({
							url: `${baseUrl}/user-center/app-file/upload-file`,
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'user': 'test'
							},
							header: {
								'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
								"Content-Type": "multipart/form-data",
							},
							success: (res) => {
								let result = JSON.parse(res.data)
								this.updateAvatar(result.datas)
							},
							fail: () => {
								uni.showToast({
									title: '操作失败',
									icon: 'error'
								})
							}
						});
					}
				});
			},
			//更新头像
			async updateAvatar(url) {
				try {
					const res = await this.$request({
						url: '/user-center/app/users/updateInfo',
						data: {
							headImgUrl: url
						}
					})
					if (res && res.respCode === 200) {
						this.initData()
					}
				} catch (e) {
					this.$refs.uToast.show({
						message: e.respMsg || '更新头像失败',
						duration: '3000',
						position: 'top'
					})
				} finally {}
			},
			editName(type, info) {
				let data = encodeURIComponent(JSON.stringify(info))
				uni.navigateTo({
					url: `/minePack/components/editName?type=${type}&info=${data}`
				})
			},
			goAccount(type) {
				let url = ''
				if (type === 'phone') {
					url = `/minePack/user/personalInformation/verifyPhone`
				} else {
					url = `/minePack/user/personalInformation/resetPassword`
				}
				uni.navigateTo({
					url: url
				})
			},
			async initData() {
				uni.showLoading({
					title: '加载中...'
				})
				try {
					const res = await this.$request({
						method: 'GET',
						url: '/api-user/app/users/info',
						data: {
							userId: this.getUserInfo.id
						}
					})
					this.personalInfo = {
						...res.datas
					}
					this.$store.commit('user/setPeronalInfo', res.datas)
					//隐藏手机号中间4位
					let mobile = res.datas.mobile
					if (mobile && mobile.length === 11) {
						this.personalInfo.mobile = mobile.substr(0, 3) + "****" + mobile.substr(7)
					}
					//设置生日
					let birthday = res.datas.birthday
					if (!birthday) {
						this.personalInfo.birthday = '请选择生日'
					}
				} catch (e) {
					this.$refs.uToast.show({
						message: e.respMsg || '获取个人信息失败',
						duration: '3000',
						position: 'top'
					})
				} finally {
					uni.hideLoading()
				}
			},
			goDetail(url) {
				if (url) {
					uni.navigateTo({
						url: url
					})
				}
			},
			carAttestation(status) {
				if (status === 0) { //未认证
					uni.navigateTo({
						url: `/indexPack/car/authenticate`
					})
					uni.setStorageSync('authSource', 'personalAuth')
				} else { //其他状态
				    uni.setStorageSync('authSource', 'personalAuth')
					uni.navigateTo({
						url: `/indexPack/car/confirm`
					})
				}
			},
			chooseBirthday() {
				if (this.personalInfo.birthday.includes('生日')) {
					this.showDatePicker = true
				} else {
					uni.showToast({
						title: '仅能修改一次',
						icon: 'error'
					})
				}
			},
			async saveBirthday() {
				try {
					const res = await this.$request({
						method: 'POST',
						url: '/user-center/app/users/updateInfo',
						data: {
							birthday: this.personalInfo.birthday
						}
					})
					if (res && res.respCode === 200) {
						uni.showToast({
							title: '修改成功',
						})
						this.initData()
					}
				} catch (e) {
					this.$refs.uToast.show({
						message: e.respMsg || '修改生日失败',
						duration: '3000',
						position: 'top'
					})
				} finally {

				}
			},
			getBirthdayDate(e) {
				const timeFormat = uni.$u.timeFormat
				this.personalInfo.birthday = timeFormat(e.value, 'yyyy-mm-dd')
				this.showDatePicker = false
				this.saveBirthday()
			},
			quitAPP() {
				// 退出登录清除store信息
				this.setToken('')
				this.setUserInfo({})
				this.setNowLocation({})
				this.setLocation({})
				uni.removeStorageSync('access_token')
				uni.removeStorageSync('userInfo')
				uni.removeStorageSync('authSource')
				uni.reLaunch({
					url: "/pages/index/index/index"
				})
				uni.$emit('refreshIndex')
			},
		},
		computed: {
			...mapGetters('user', ['getUserInfo']),
			...mapGetters('global', ['getSystemInfo']),
			setStatus() {
				return function(status) {
					if (status === -1) {
						return '认证失败'
					} else if (status === 0) {
						return '未认证'
					} else if (status === 1) {
						return '已认证'
					} else if (status === 2) {
						return '待审核'
					} else {
						return ''
					}
				}
			}
		},
		onShow() {
			this.initData()
		},
		onLoad() {
			this.initData()
			uni.$on('refreshData', res => {
				this.initData()
			})
		}
	}
</script>

<style lang="scss" scoped>
	.page-wrapper {
		padding-bottom: 70px;

		.item {
			margin-bottom: 20rpx;
			background-color: #FFFFFF;

			.item-title {
				font-size: 28rpx;
				color: rgba(0, 0, 0, 0.85);
				margin-left: 32rpx;
				padding-top: 32rpx;
				margin-bottom: 38rpx;
				text-shadow: 0 0 0.1px currentcolor;
			}

			.head-img {
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
			}

			.one-line {
				display: flex;
				height: 88rpx;
				justify-content: space-between;
				align-items: center;

				.name {
					font-size: 28rpx;
					color: rgba(0, 0, 0, 0.85);
					margin-left: 32rpx;
					flex: 1;
					text-shadow: 0 0 0.1px currentcolor;
				}

				.setting {
					font-size: 24rpx;
					font-weight: 400;
					margin-right: 30rpx;
					display: flex;

					.do {
						margin-right: 4px;
					}

					.undo {
						color: #F83E48;
					}

					.u-setting {
						/deep/.uni-icons {
							color: #909399 !important;
						}
					}
				}
			}
		}

		.action-bottom {
			height: 70px;
			width: 100%;
			position: fixed;
			bottom: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #FFFFFF;

			/deep/ .u-button {
				width: 90% !important;
			}
		}
	}
</style>